﻿using Autofac.Core;
using Currency.Infra.EntityFramework;
using Currency.Services.Shared;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace Autofac
{
    /// <summary>
    /// 注入依赖模块
    /// </summary>
    public static class AutofacModuleRegister
    {
        /// <summary>
        /// 统一注册通用模块
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <param name="serverInfo"></param>
        /// <param name="completedExecute"></param>
        /// <returns></returns>
        public static ContainerBuilder RegisterModules(this ContainerBuilder builder, IServiceCollection services, Action<ContainerBuilder> completedExecute = null)
        {
            var configuration = services.GetConfiguration();//获取配置
            var serviceInfo = services.GetServiceInfo();//获取程序信息

            var applicationAssembly = Assembly.Load(serviceInfo.AssemblyFullName.Replace("WebApi", "Services"));//获取Services程序集
            //筛选AutofacServicesModule
            var applicationModelType = applicationAssembly.GetTypes().FirstOrDefault(m =>
                m.FullName != null &&
                typeof(AutofacServicesModule).IsAssignableFrom(m) &&
                !m.IsAbstract
            );

            builder.RegisterModule<AutofacEfCoreModule>();//注入EF
            builder.RegisterModule(Activator.CreateInstance(applicationModelType, configuration, serviceInfo) as IModule);

            completedExecute?.Invoke(builder);

            return builder;
        }
    }
}
